package com.unionx.unionxuf.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.unionx.unionxuf.entity.UaAccount;
import com.unionx.unionxuf.entity.User;

@Repository("LoginDao")
public class LoginDaoImpl implements LoginDao {
	
	@Autowired(required = true)
	private JdbcTemplate jdbcTemplate;

	@Autowired(required = true)
	private DataSourceTransactionManager remotetransactionManager;

	DefaultTransactionDefinition def = new DefaultTransactionDefinition();

	private Map<String, Object> map = new HashMap<String, Object>();


	@SuppressWarnings({ "rawtypes", "unused" })
	public Object getAllCorpInfo(Integer pageSize,Integer pageNumber) {
		map.clear();
		TransactionStatus status = remotetransactionManager.getTransaction(def);
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
		try {

			List  list = jdbcTemplate.queryForList("select cacc_id,cacc_name from ua_account");
			Map<String, Object> map = new HashMap<String, Object>();
			int total = 0;
	        int curr =0;
			List<UaAccount> acList = new ArrayList<UaAccount>();
			 
	        for(int i=(pageNumber-1)*pageSize;i<list.size();i++){
             if(curr==pageSize){
            	 break;
             }else{
		     Map  uaMap=(Map) list.get(i);
			 UaAccount ac = new UaAccount();
			 ac.setcAccId((String)uaMap.get("cAcc_id"));
			 ac.setcAccName((String)uaMap.get("cAcc_Name"));
			 acList.add(ac); 
			 curr++;
             	}
             }
			 int  count  =list.size();
			 if(pageSize>count){
			 total =1;
			 }
			 if(count%pageSize==0){
			 total=count/pageSize;
			 }
			 if(count%pageSize>0){
			 total=count/pageSize+1;
			 }
		    remotetransactionManager.commit(status);
			map.put("status", 0);
			map.put("message", "方法请求成功");
			map.put("rows", acList);
			map.put("total", total);
			return map;
		} catch (EmptyResultDataAccessException e) {
			remotetransactionManager.rollback(status);
			map.put("status", 1);
			map.put("message", "方法请求失败");
			map.put("data", "500");
			return map;
		}
	}

	@Override
	public int getCorpCount() {
		// TODO Auto-generated method stub
		return jdbcTemplate.queryForInt("select count(1) from ua_account");
	}
	
	public Object getUserInfo(String username, String password) {
		map.clear();
		TransactionStatus status = remotetransactionManager.getTransaction(def);
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
		HashMap<String, Object> result = null;
		try {
			//sql语句需要改
			result = (HashMap<String, Object>) jdbcTemplate.queryForMap(
					"select cuser_id,cuser_name,cUserHand from ua_user where cuser_name= ? and cUserHand= ?",
					new Object[] { username, password });
			remotetransactionManager.commit(status);
			map.put("status", 0);
			map.put("message", "方法请求成功");
			map.put("data", result);
			return map;
		} catch (EmptyResultDataAccessException e) {
			remotetransactionManager.rollback(status);
			map.put("status", 1);
			map.put("message", "方法请求失败");
			map.put("data", "请检查输入的信息");
			return map;
		}
	}

	public Object updateUserPassword(String userid, String password) {
		map.clear();
		TransactionStatus status = remotetransactionManager.getTransaction(def);
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
		/*
		 * SELECT * FROM [Master].[dbo].[SYSPROCESSES] WHERE [DBID] IN ( SELECT
		 * [DBID] FROM [Master].[dbo].[SYSDATABASES] WHERE NAME='databaseName'
		 * and hostname='hanrui-pc' )
		 */

		try {

			jdbcTemplate.update("update ua_user set cUserHand= ? where cuser_id = ?",
					new Object[] { password, userid });
			remotetransactionManager.commit(status);
			map.put("status", 0);
			map.put("message", "方法请求成功");
			map.put("data", userid);
			return map;
		} catch (EmptyResultDataAccessException e) {
			
			remotetransactionManager.rollback(status);
			map.put("status", 0);
			map.put("message", "方法请求失败");
		    map.put("data","500");
			return map;
		}
	}

	@Override
	public Object getAllCorps() {

		map.clear();
		TransactionStatus status = remotetransactionManager.getTransaction(def);
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
		 List<UaAccount> acList = new ArrayList<UaAccount>();
		try {

			List  list = jdbcTemplate.queryForList("select cAcc_Name,cacc_id from ua_account");
			Map<String, Object> map = new HashMap<String, Object>();		
	       
			 for(int i=0;i<list.size();i++){
             Map  uaMap=(Map) list.get(i);
			 UaAccount ac = new UaAccount();
			 ac.setcAccId((String)uaMap.get("cAcc_id"));
			 ac.setcAccName((String)uaMap.get("cAcc_Name"));
			 acList.add(ac); 
			 }
		    remotetransactionManager.commit(status);
			map.put("status", 0);
			map.put("message", "方法请求成功");
			map.put("data", acList);

			return acList;
		} catch (EmptyResultDataAccessException e) {
			remotetransactionManager.rollback(status);
			map.put("status", 1);
			map.put("message", "方法请求失败");
			map.put("data", "500");
			return acList;
		}
	}

	@Override
	public User getUser(String ccusername, String ccuserpwd) {
		// TODO Auto-generated method stub
		map.clear();
		TransactionStatus status = remotetransactionManager.getTransaction(def);
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
		final User user = new User();
		try {
			
			
			jdbcTemplate.query("select cuser_id,cuser_name,cUserHand from ua_user where cuser_name= ? and cUserHand= ?",
					new Object[] { ccusername, ccuserpwd },
			                    new RowCallbackHandler() {
			                        public void processRow(ResultSet rs) throws SQLException {
			                            user.setId(rs.getString(1));
			                            user.setName(rs.getString(2));
			                            user.setPwd(rs.getString(3));
			                        }
			                    });


		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
		return user;
	}



}